import 'package:riverpod/riverpod.dart';
import '../models/quiz_question.dart';
import '../models/learning_record.dart';
import '../services/word_service.dart';
import '../services/storage_service.dart';
import 'word_provider.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../services/daily_quiz_service.dart';
import '../models/daily_quiz.dart';

final quizQuestionsProvider = FutureProvider.family<List<QuizQuestion>, QuizParams>((ref, params) async {
  final wordService = ref.watch(wordServiceProvider);
  return wordService.getQuizQuestions(params.category, params.count);
});

final quizStateProvider = StateNotifierProvider<QuizStateNotifier, QuizState>((ref) {
  return QuizStateNotifier(ref.watch(storageServiceProvider));
});

class QuizParams {
  final String category;
  final int count;

  const QuizParams({
    required this.category,
    required this.count,
  });
}

class QuizState {
  final List<QuizQuestion> questions;
  final int currentQuestionIndex;
  final List<int?> userAnswers;
  final bool isCompleted;
  final int score;

  const QuizState({
    this.questions = const [],
    this.currentQuestionIndex = 0,
    this.userAnswers = const [],
    this.isCompleted = false,
    this.score = 0,
  });

  QuizState copyWith({
    List<QuizQuestion>? questions,
    int? currentQuestionIndex,
    List<int?>? userAnswers,
    bool? isCompleted,
    int? score,
  }) {
    return QuizState(
      questions: questions ?? this.questions,
      currentQuestionIndex: currentQuestionIndex ?? this.currentQuestionIndex,
      userAnswers: userAnswers ?? this.userAnswers,
      isCompleted: isCompleted ?? this.isCompleted,
      score: score ?? this.score,
    );
  }

  QuizQuestion? get currentQuestion {
    if (currentQuestionIndex >= questions.length) return null;
    return questions[currentQuestionIndex];
  }

  bool get hasNext => currentQuestionIndex < questions.length - 1;
  bool get hasPrevious => currentQuestionIndex > 0;
}

class QuizStateNotifier extends StateNotifier<QuizState> {
  final StorageService _storageService;

  QuizStateNotifier(this._storageService) : super(const QuizState());

  void initializeQuiz(List<QuizQuestion> questions) {
    state = QuizState(
      questions: questions,
      userAnswers: List.filled(questions.length, null),
    );
  }

  void answerQuestion(int answerIndex) {
    final updatedAnswers = List<int?>.from(state.userAnswers);
    updatedAnswers[state.currentQuestionIndex] = answerIndex;
    
    state = state.copyWith(userAnswers: updatedAnswers);
  }

  void nextQuestion() {
    if (state.hasNext) {
      state = state.copyWith(currentQuestionIndex: state.currentQuestionIndex + 1);
    }
  }

  void previousQuestion() {
    if (state.hasPrevious) {
      state = state.copyWith(currentQuestionIndex: state.currentQuestionIndex - 1);
    }
  }

  Future<void> completeQuiz() async {
    int score = 0;
    for (int i = 0; i < state.questions.length; i++) {
      final userAnswer = state.userAnswers[i];
      if (userAnswer != null && state.questions[i].isCorrectAnswer(userAnswer)) {
        score++;
      }
      
      // Save learning record
      final record = LearningRecord(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        wordId: state.questions[i].id,
        studiedAt: DateTime.now(),
        isCorrect: userAnswer != null && state.questions[i].isCorrectAnswer(userAnswer),
        difficulty: state.questions[i].difficulty,
      );
      
      await _storageService.addLearningRecord(record);
    }
    
    state = state.copyWith(
      isCompleted: true,
      score: score,
    );
  }

  void resetQuiz() {
    state = const QuizState();
  }
}

// 每日测验服务Provider
final dailyQuizServiceProvider = Provider<DailyQuizService>((ref) {
  final storageService = ref.watch(storageServiceProvider);
  return DailyQuizService(storageService);
});

// 今日测验Provider
final todayQuizProvider = FutureProvider<DailyQuiz>((ref) async {
  final service = ref.watch(dailyQuizServiceProvider);
  return service.getTodayQuiz();
});

// 今日测验完成状态Provider
final todayQuizCompletedProvider = FutureProvider<bool>((ref) async {
  final service = ref.watch(dailyQuizServiceProvider);
  return service.hasTodayQuizCompleted();
}); 